package com.book.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.Snowflake;
import com.book.util.JsonResult;
import com.book.vo.CodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author SuperYu  2024/8/13
 */
@RestController
@RequestMapping("/code")
@CrossOrigin(origins = "*", originPatterns = "*", allowedHeaders = "*")
public class CaptchaController {

    @Resource
    LineCaptcha lineCaptcha;

    @Resource
    Snowflake snowflake;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @GetMapping("/getCode")
    public JsonResult<CodeVo> getCode(HttpServletResponse response) throws IOException {
        //图形验证码写出，可以写出到文件，也可以写出到流
        // lineCaptcha.write("d:/line.png");
        //输出code
        lineCaptcha.createCode();
        String code = lineCaptcha.getCode();
        Console.log("生成的验证码："+ code );

        String imageBase64Data = lineCaptcha.getImageBase64Data();

        System.out.println("生成的base64格式："+imageBase64Data);
        // 我们要把生成的验证码存入redis里。
        // long id = snowflake.nextId();
        String id = snowflake.nextIdStr();
        System.out.println("redis里面的key:"+id);
        // 把验证码存入redis中，过期时间为2分钟
        stringRedisTemplate.opsForValue().set(id,code,2 , TimeUnit.MINUTES);

        CodeVo codeVo = new CodeVo();
        codeVo.setId(id);
        codeVo.setCodeImg(imageBase64Data);

        return JsonResult.ok(200,codeVo) ;
    }

    @GetMapping("/verify")
    public JsonResult verify(String code) {
        //输出code
        Console.log("前端输入的码：" + code);
        //验证图形验证码的有效性，返回boolean值
        boolean f = lineCaptcha.verify(code);
        System.out.println("验证结果：" + f);

        //重新生成验证码
        // lineCaptcha.createCode();
        // lineCaptcha.write("d:/line.png");
        // //新的验证码
        // Console.log(lineCaptcha.getCode());
        // //验证图形验证码的有效性，返回boolean值
        // lineCaptcha.verify("1234");

        return null;
    }


}
